# -*- coding: utf-8 -*-
import sys
import conf
from syslog import *
from urllib2 import HTTPError,URLError
from exception import LoginException,ConnectException,TryOutException


try:
    import twitter
except ImportError,cause:
    sys.stderr.write("ImportError: Module is not present %s" % cause)
    sys.exit(1)

class TwitterManager():
    def __init__(self):
        # Twitter API
        config = conf.get_config()
        u = self.userlogin = config.get("login","userlogin")
        p = self.password  = config.get("login","password")
        self.api = twitter.Api(username=u,password=p)

        # Times to retry connect
        self.connect_try = 0
        self.max_tries = 1
        self.trying_connect = False

    def check_user(self):
        if not self.userlogin or not self.password:
            raise LoginException("Usuário não autenticado\n")

    def register_connenct(self):
        if self.connect_try >= self.max_tries:
            raise TryOutException("Tentivas excedidas\n")
            self.trying_connect = False
            self.connect_try = 0
        self.trying_connect = True
        self.connect_try += 1

    def get_timeline(self):
        try:
            self.register_connenct()            
            text_list = self.api.GetFriendsTimeline()
        except HTTPError,cause:
            raise TryOutException("Falhou ao conectar")
            syslog(LOG_ERR,"HTTPError: %s (trying again)\n" % cause)
            self.get_timeline()
        except URLError,cause:
            raise TryOutException("Falhou ao conectar")
            syslog(LOG_ERR,"URLError: %s (trying again)\n" % cause)
            self.get_timeline()
        except twitter.TwitterError,cause:
            raise TryOutException("Falhou ao conectar")
            syslog(LOG_ERR,"TwitterError: %s (trying again)\n" % cause)
            self.get_timeline()
            
        self.trying_connect = False
        self.connect_try = 0
        return [(i.GetUser().GetProfileImageUrl(),i.text) for i in text_list]
    
    def send_message(self,msg,user = None):
        try:
            self.register_connenct()
            self.api.PostUpdate(msg)
        except HTTPError,cause:
            raise TryOutException("Falhou ao conectar")
            syslog(LOG_ERR,"HTTPError: %s (trying again)\n" % cause)
            self.get_timeline()
        except URLError,cause:
            raise TryOutException("Falhou ao conectar")
            syslog(LOG_ERR,"URLError: %s (trying again)\n" % cause)
            self.get_timeline()
        except twitter.TwitterError,cause:
            raise TryOutException("Falhou ao conectar")
            syslog(LOG_ERR,"TwitterError: %s (trying again)\n" % cause)
            self.get_timeline()

        self.trying_connect = False
        self.connect_try = 0            
